package com.imstlife.vending.activity;

import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextClock;
import android.widget.TextView;

import com.google.gson.Gson;
import com.imstlife.vending.R;
import com.imstlife.vending.api.MarvAPI;
import com.imstlife.vending.bean.UpLogBean;
import com.imstlife.vending.bean.UpdataLog;
import com.imstlife.vending.dialog.PasswordDialog;
import com.imstlife.vending.listener.MyDrinkListListener;
import com.imstlife.vending.sgy.logger.LocalLog;
import com.imstlife.vending.utils.AppUtil;
import com.imstlife.vending.utils.Cof;
import com.imstlife.vending.utils.DialogUtil;
import com.imstlife.vending.utils.DownLoadTask;
import com.imstlife.vending.utils.DrinkCountUtil;
import com.imstlife.vending.utils.HttpUtil;
import com.imstlife.vending.utils.RootShellCmd;
import com.imstlife.vending.utils.SharePersistentUtil;
import com.imstlife.vending.utils.T;
import com.imstlife.vending.view.MyDrinkListView;
import com.imstlife.vending.view.UpApkDialog;
import com.imstlife.vending.vo.CheckUpdateRespone;
import com.imstlife.vending.vo.DrinkInfo;
import com.imstlife.vending.vo.DrinkListVo;
import com.imstlife.vending.wifi.NetThread;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

import settings.SettingsActivity;

/**
 * Created by lihaifeng on 16/10/27.
 */
public class DrinksActivity extends BaseActivity  implements MyDrinkListListener, NetThread.OnNetChangeListener {

    /**
     * 商品列表
     */
    private List<DrinkInfo> drinkList;

    private static String TAG = "DrinksActivity";

    /**
     * 接收推送广播
     */
    private MainAcNotificationReceiver receiver;
    private DialogUtil dialogUtil = new DialogUtil();

    private TextClock tvClock;

    private Receiver receiver2;

    /**
     * 自定义商品列表  可动态设置商品数量  可动态设置货道规格（每行商品数量不同）商品变动时列表中只有该商品刷新UI
     */
    private MyDrinkListView drinkListView;

    /**
     * 屏幕的宽
     */
    private int width;
    private ImageView vendingWifi;
    private TextView wifiTv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_drinks);

        width = getWindowManager().getDefaultDisplay().getWidth();

        initData();
        initView();
        Log.i(TAG, "onCreate");

        if (HttpUtil.isNetworkAvailable(this)) {
            checkUpdate();
        }
        IntentFilter intentFilter = new IntentFilter();
        receiver2 = new Receiver();
        intentFilter.addAction("ACTION_LOG");//上传日志
        intentFilter.addAction("ACTION_UPLOADLOG_NEW");//上传日志
        registerReceiver(receiver2, intentFilter);
    }
    Gson gson = new Gson();
    public class Receiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if ("ACTION_UPLOADLOG_NEW".equals(action)) {
                Bundle bundle = intent.getExtras();
                String data = bundle.getString("data");
                UpLogBean ulb = gson.fromJson(data,UpLogBean.class);
                List<String> list = AppUtil.getTimeList(ulb.getData().getStartTime(),AppUtil.isOutTime(ulb.getData().getStartTime(),ulb.getData().getEndTime()));
                AppUtil.sendLog(list,ulb.getHashValue(),ulb.getData().getId());
            }
            if ("ACTION_LOG".equals(action)) {
                Bundle bundle = intent.getExtras();
                String data = bundle.getString("data");
                UpLogBean ulb = gson.fromJson(data,UpLogBean.class);
                List<String> list = AppUtil.getTimeList(ulb.getData().getStartTime(),AppUtil.isOutTime(ulb.getData().getStartTime(),ulb.getData().getEndTime()));
                if (ulb.getActionName().equals("uploadLogDetail")){
                    AppUtil.sendLog(ulb.getData().getId(),list,ulb.getData().getEndTime(),DrinksActivity.this,true);
                }else{
                    AppUtil.sendLog("",list,ulb.getData().getEndTime(),DrinksActivity.this,false);
                }
            }
        }
    }



    private int apksize;//apk大小
    private boolean downApkFlagProgressDialog = true;
    //检查更新
    private void checkUpdate() {
        String url = Cof.Interface.URL_CHECK_UPDATE;
        String deviceId = SharePersistentUtil.getSharePersistentString(DrinksActivity.this, Cof.KEY_DEVICE_ID);
        int versionCode = AppUtil.getVersionCode(DrinksActivity.this);
        String versionName = AppUtil.getVersionName(DrinksActivity.this);
        MarvAPI.getInstance().checkUpdate(url, deviceId, Cof.KEY, versionName, versionCode + "", new MarvAPI.APIListener() {
            @Override
            public void onSuccess(Object data) {
                final CheckUpdateRespone respone = (CheckUpdateRespone) data;

                if ("0".equals(respone.getStatus())) {
                    UpApkDialog ld = UpApkDialog.getlmld(DrinksActivity.this);
                    ld.setInterface(new UpApkDialog.getMqttLogin() {
                        @Override
                        public void showApk() {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    downApkFlagProgressDialog = true;
                                    setProgressDialog();
                                }
                            });
                            downLoadFile(respone.getData().getDownLoadUrl(), "vending.apk",
                                    2);
                        }
                    });
                    ld.setCancelable(false);
                    ld.show();
                } else {
                }
            }

            @Override
            public void onFailure(String msg) {
            }

            @Override
            public void onNetError(String msg) {
            }
        });
    }
    boolean interceptFlag = false;
    //下载apk
    protected void downLoadFile(final String httpUrl, final String apkName,
                                final int handlerType) {
        try {
            // Log.i("lhf", "haha");
            Log.e("apkurl", httpUrl);
            URL url = new URL(httpUrl);
            HttpURLConnection conn = (HttpURLConnection) url
                    .openConnection();
            conn.connect();
            float length = conn.getContentLength();
            InputStream is = conn.getInputStream();
            File file = new File("/sdcard/myrunning_apk/");
            if (!file.exists()) {
                file.mkdir();
            }
            String apkPath = "/sdcard/myrunning_apk/" + apkName;
            File apkFile = new File(apkPath);
            FileOutputStream fos = new FileOutputStream(apkFile);
            int count = 0;
            byte buf[] = new byte[10240];
            do {
                if (!downApkFlagProgressDialog) {
                    return;
                }
                int numread = is.read(buf);
                count += numread;
                float b = count * 100 / length + 0.5f;
                int progress = (int) b;
                apksize = (int) length;
                Log.i("lhf", "当前下载进度" + progress+"  c="+count +"  s="+apksize);
                fos.write(buf, 0, numread);
                Message msg = new Message();
                msg.what = handlerType;
                msg.obj = apkFile;
                msg.arg1 = count;
                msg.arg2 = progress;
                mHandler2.sendMessage(msg);
            } while (!interceptFlag /*&& is.read(buf)!= -1*/);// 中断下载时使用

            fos.close();
            is.close();

            //openFile(apkFile);

        } catch (Exception e) {
            e.printStackTrace();
        }


    }
    ProgressDialog m_pDialog;
    //自动更新弹框
    public void setProgressDialog() {
        // 创建ProgressDialog对象
        m_pDialog = new ProgressDialog(DrinksActivity.this);

        // 设置进度条风格，风格为长形
        m_pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);

        // 设置ProgressDialog 标题
        m_pDialog.setTitle("正在更新");

        // 设置ProgressDialog 进度条进度
        m_pDialog.setProgress(100);

        // 设置ProgressDialog 的进度条是否不明确
        m_pDialog.setIndeterminate(false);

        // 设置ProgressDialog 是否可以按退回按键取消
        m_pDialog.setCancelable(true);

        m_pDialog.setCancelable(false);

        m_pDialog.setButton(DialogInterface.BUTTON_POSITIVE, "取消本次更新", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface d, int i) {
                downApkFlagProgressDialog = false;
                m_pDialog.dismiss();
            }
        });

        // 让ProgressDialog显示
        m_pDialog.show();
        Window window = m_pDialog.getWindow();
        window.setGravity(Gravity.CENTER);
        //window.setWindowAnimations(R.style.mystyle);
        WindowManager.LayoutParams params = window.getAttributes();
        params.width = WindowManager.LayoutParams.WRAP_CONTENT;
        params.height = WindowManager.LayoutParams.WRAP_CONTENT;
        window.setAttributes(params);
    }




    /**
     * 加载数据
     */
    private void initData() {

        drinkList = ((DrinkListVo) getIntent().getSerializableExtra("drinks")).getDrinkList();

        }

    /**
     * 加载视图
     */
    private void initView() {

            drinkListView = (MyDrinkListView) findViewById(R.id.drinklist);
          drinkListView.configView(drinkList, deviceModel, width,this);
        vendingWifi = (ImageView) findViewById(R.id.vending_wifi);
        wifiTv = (TextView) findViewById(R.id.wifi_tv);
        NetThread.getInstance().start();
        NetThread.getInstance().setOnNetChangeListener(this);
        WifiTvThread wtt = new WifiTvThread();
        wtt.start();
        tvClock = (TextClock) findViewById(R.id.tv_ac_drinks_clock);
        tvClock.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {

//                PasswordDialog passwordDialog = PasswordDialog.getIns(DrinksActivity.this);
//                passwordDialog.show();
                dialogUtil.administratorcheck(DrinksActivity.this, new DialogUtil.main_administratorcheck() {
                    @Override
                    public void ifcorrect() {
                        Intent intent = new Intent(DrinksActivity.this, SettingsActivity.class);
                        Bundle bundle = new Bundle();
                        bundle.putSerializable("drinks",(DrinkListVo) getIntent().getSerializableExtra("drinks"));
                        intent.putExtra("deviceModel",getIntent().getStringExtra("deviceModel"));
                        intent.putExtras(bundle);
                        startActivity(intent);
                        overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
                    }

                    @Override
                    public void iferror() {
                        T.showShort2(DrinksActivity.this, "密码不正确");
                    }

                    @Override
                    public void ifnull() {
                        T.showShort2(DrinksActivity.this, "密码不能为空");
                    }
                }, 0, Cof.adminpwd, false);

                return false;
            }
        });
    }




    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {

                default:
                    break;
            }
        }
    };

    @Override
    protected void onResume() {

        Log.i(TAG, "onResume");
        super.onResume();
        drinkListView.refView();
    }

    @Override
    protected void onPause() {
        Log.i(TAG, "onPause");
        super.onPause();
    }

    /**
     *  自定义商品列表的商品点击事件
     * @param drinkInfo
     */
    @Override
    public void onItemClick(DrinkInfo drinkInfo) {
            if (DrinkCountUtil.getDrinkCountByNum(this,drinkInfo.getNum()+"")>0 && drinkInfo.getPrice() != 0) {
                Intent intent = new Intent(this, DrinkInfoActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("drinkinfo", drinkInfo);
                bundle.putString("deviceModel",deviceModel);
                bundle.putString("syncUrl",syncUrl);
                bundle.putString("notifyUrl",notifyUrl);
                intent.putExtras(bundle);
                startActivity(intent);
            }else{
                T.showShort(DrinksActivity.this,getResources().getString(R.string.sell_null));
            }


    }



    @Override
    public void onNetChange(int state) {
        super.onNetChange(state);
        switch (state){

        }
    }

    /**
     * 商品列表出货成功或失败，只吐司 不返回
     * @param state
     */
    @Override
    public void outResult(int state) {
        super.outResult(state);
        Log.i(TAG,"outResult"+state);
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.i(TAG,"onDestory...");
        unregisterReceiver(receiver2);
    }

    @Override
    public void onNetChange(NetworkInfo.State state, int type, int wifiLevel) {
        NetThread.getInstance().updateWifiView(vendingWifi, state, type, wifiLevel);
    }
    private Handler mHandler2 = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what){
                case 1:
                    if (msg.obj.toString().equals("-- --")) {
                        wifiTv.setTextColor(Color.RED);
                    } else {
                        wifiTv.setTextColor(Color.WHITE);
                    }
                    wifiTv.setText(msg.obj.toString() + "ms");
                    break;
                case 2:
                    if (msg.arg2 <= 100) {
                        Log.e("updata", msg.arg2 + "   " + m_pDialog.getProgress());
                        m_pDialog.setProgress(msg.arg2);
                    }

                    if (msg.arg2 == 100 && msg.arg1 > apksize-10) {
                        m_pDialog.cancel();
                        interceptFlag = false;
                        RootShellCmd.install("/sdcard/myrunning_apk/vending.apk", "com.imstlife.vending");
                    }
                    break;
            }
        }
    };
    public void getNetworkDelayPingOneOneFour() {
        String delay = new String();
        Process p = null;
        try {
            String ip = "114.114.114.114";
            Log.e("nett", "开始Ping 114");
            p = Runtime.getRuntime().exec("/system/bin/ping -c 1 -w 5 " + ip);
            BufferedReader buf = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String str;
            if ((buf.readLine()) == null) {
                Log.e("nett", "Ping 114,ping不通");
            }
            while ((str = buf.readLine()) != null) {
                Log.e("nett", "114获取到数据" + str);
                if (str.contains("received")) {
                    int i = str.indexOf(",");
                    int j = str.indexOf("received", i);
                    int received = Integer.parseInt(str.substring(i + 1, j).trim());
                    if (0 == received) {
                        Message msg = Message.obtain();
                        msg.what = 1;
                        msg.obj = "-- --";
                        mHandler2.sendMessageDelayed(msg, 100);
                    }
                }
                if (str.contains("avg")) { //从第21个字符开始查找，“/”的位置，包括第21个字符
                    int i = str.indexOf("/", 20);
                    int j = str.indexOf(".", i); //截取str中从beginIndex开始至endIndex结束时的字符串， beginIndex =< str的值 < endIndex并将其赋值给str
                    Log.e("nett", "Ping 114延迟:" + str.substring(i + 1, j));
                    Message msg = Message.obtain();
                    msg.what =1;
                    msg.obj = str.substring(i + 1, j);
                    mHandler2.sendMessageDelayed(msg, 100);
                    Log.e("nett", "Ping 114的平均延迟为：" + str.substring(i + 1, j));
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (p != null) {
                p.destroy();
            }
        }
    }
    public class WifiTvThread extends Thread {
        @Override
        public void run() {
            super.run();
            while (true) {
                if (HttpUtil.isNetworkAvailable(DrinksActivity.this)) {
                    getNetworkDelayPingOneOneFour();
                }else{
                    Message msg = Message.obtain();
                    msg.what = 1;
                    msg.obj = "-- --";
                    mHandler2.sendMessageDelayed(msg, 100);
                }
                try {
                    sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
